from django.http import JsonResponse
from django.shortcuts import render

from firstplan import models
from firstplan.mine.myform import PlanList
from firstplan.mine.pagination import Pagination


def plan_list(request):
    """计划列表"""
    title = '计划列表'
    form = PlanList()
    queryset = models.PlanEvent.objects.all().order_by("important","-date")
    context = {
        "queryset": queryset,
        "form":form,
        'title': title
    }
    return render(request,'plan_list.html',context)


def plan_add(request):
    """计划添加"""
    form = PlanList(data=request.POST)
    if form.is_valid():
        form.save()
        return JsonResponse({"status":True})
    return JsonResponse({"status":False,'error':form.errors})


def plan_detail(request):
    """计划详情"""
    id = request.GET.get("uid")
    row_obj = models.PlanEvent.objects.filter(id=id).values("event","important","deduct_point").first()
    if not row_obj:
        return JsonResponse({"status": False, 'tips': "数据不存在"})
    return JsonResponse({"status": True, 'data': row_obj})


def plan_edit(request):
    """计划修改"""
    id = request.GET.get("uid")
    row_obj = models.PlanEvent.objects.filter(id=id).first()
    if not row_obj:
        return JsonResponse({"status":False,'tips':"数据不存在"})
    form = PlanList(data=request.POST,instance=row_obj)
    if form.is_valid():
        form.save()
        return JsonResponse({"status": True})
    return JsonResponse({"status": False, 'error': form.errors})


def plan_delete(request):
    """计划删除"""
    id = request.GET.get("uid")
    print(id)
    exists = models.PlanEvent.objects.filter(id=id).exists()
    if not exists:
        return JsonResponse({"status":False,"tips":"数据不存在"})
    models.PlanEvent.objects.filter(id=id).delete()
    return JsonResponse({"status":True})